package com.tcm.user.authentication;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.base.core.codec.Md5Utils;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.base.genid.generator.UidGenerator;
import com.tcm.user.model.query.LoginAuthQuery;
import com.tcm.user.model.entity.LoginAuth;
import com.tcm.user.constants.enums.BusinessCodeEnum;
import com.tcm.user.constants.enums.SignupTypeEnum;
import com.tcm.user.factory.Signup;
import com.tcm.user.persistence.LoginAuthPersisService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PasswordSignup implements Signup {

    @Autowired
    private LoginAuthPersisService loginAuthPersisService;

    @DubboReference(version = "0.0.1-beta", group = "cached-uid", check = false, retries = 3)
    private UidGenerator uidGenerator;

    @Override
    public R save(LoginAuthQuery loginAuthQuery) {
        if(ObjectUtil.isEmpty(loginAuthQuery.getClientType())){
            return R.fail(BusinessCodeEnum.IDENTITY_TYPE_PARAMS_NOT_FOUND);
        }
        if(ObjectUtil.isEmpty(loginAuthQuery.getPrincipal())){
            return R.fail(BusinessCodeEnum.IDENTIFIER_NOT_EXISTS);
        }
        if(ObjectUtil.isEmpty(loginAuthQuery.getCredential())){
            return R.fail(BusinessCodeEnum.PASSWORD_NOTFOUND);
        }
        try{
            //查询登录账号是否存在
            LoginAuth login = loginAuthPersisService.findByUsername(loginAuthQuery.getPrincipal(),
                    loginAuthQuery.getClientType());
            if(ObjectUtil.isNotEmpty(login)){
                return R.fail(BusinessCodeEnum.IDENTIFIER_EXISTS);
            }
            String password = loginAuthQuery.getCredential();
            String salt = RandomUtil.randomNumbers(6);
            password = Md5Utils.md5((password + salt));
            login = new LoginAuth();
            login.setCredential(password);
            login.setSalt(salt);
            //保存登录账号信息
            login.setId(uidGenerator.getUID());
            login.setClientType(loginAuthQuery.getClientType());
            login.setUsername(loginAuthQuery.getPrincipal());
            loginAuthPersisService.save(login);
            return R.success(login.getId());
        }catch (ServiceException e){
            return R.fail(e.getResult().getCode(), e.getMessage());
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    @Override
    public String supports() {
        return SignupTypeEnum.PWD.type();
    }
}
